package com.media.module.activity;

import java.util.List;
import com.media.module.R;
import com.media.module.model.CameraMode;
import com.media.module.model.OutputFormatMode;
import com.media.module.utils.MediaConst;
import com.media.module.utils.SupportedSizesReflect;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.media.CamcorderProfile;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
	private Button mbtnStart;
	private TextView tvPath;
	private Button mbtnAudio;
	private TextView mtvPx;

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			Window window = getWindow();
			// Translucent status bar
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
		}
		setContentView(R.layout.activity_main);
		mbtnStart = (Button) findViewById(R.id.btn_start);
		tvPath = (TextView) findViewById(R.id.tv_path);
		mbtnAudio = (Button) findViewById(R.id.btn_audio);
		mtvPx = (TextView) findViewById(R.id.tv_px);
		Camera camera = Camera.open(getCameraId(false));
		List<Size> supportedPictureSizes = SupportedSizesReflect.getSupportedPictureSizes(camera.getParameters());
//		List<Size> supportedPreviewSizes = SupportedSizesReflect.getSupportedPreviewSizes(camera.getParameters());
		StringBuffer strBuff = new StringBuffer();

		Size[] sizeArr = supportedPictureSizes.toArray(new Size[supportedPictureSizes.size()]);
//		sizeArr = supportedPreviewSizes.toArray(new Size[supportedPreviewSizes.size()]);
		for (int i = 0; i < sizeArr.length -1; i++) {
			for (int j = 0; j < sizeArr.length -1; j++) {
				if(sizeArr[j].height > sizeArr[j + 1].height){
					Size size = sizeArr[j];
					sizeArr[j] = sizeArr[j + 1];
					sizeArr[j + 1] = size;
				}
			}
		}

		for (Size size : sizeArr) {
			strBuff.append(size.height +"X"+size.width + ";");
		}
		
		DisplayMetrics displayMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
		strBuff.append("\n\r"+displayMetrics.heightPixels+"X"+displayMetrics.widthPixels);
		mtvPx.setText(strBuff);
		mbtnStart.setOnClickListener(new View.OnClickListener() {

			@SuppressWarnings("unused")
			@Override
			public void onClick(View v) {
				CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
				profile = CamcorderProfile.get(CamcorderProfile.QUALITY_LOW);
				Intent intent = new Intent();
				intent.setClass(MainActivity.this, CameraActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString(MediaConst.OUTPUT_PHOTO_PATH, Environment.getExternalStorageDirectory().getAbsolutePath()+"/photo");
				bundle.putInt(MediaConst.OUTPUT_PHOTO_WIDTH_PX, 3264);
		        bundle.putInt(MediaConst.OUTPUT_PHOTO_HEIGHT_PX, 2448);
				bundle.putBoolean(MediaConst.SHOW_CAMERA_PREVIEW, true);
				bundle.putBoolean(MediaConst.SHOW_PIXELS_SET, true);
				intent.putExtra(MediaConst.BUNDLE_DATA, bundle);
				startActivityForResult(intent, 1);
				
//				Intent intent = new Intent();
//				intent.setClass(MainActivity.this, CameraActivity.class);
//				Bundle bundle = new Bundle();
//				bundle.putInt(MediaConst.CAMERA_TYPE_VALUE, CameraMode.VIDEO.getId());
//				bundle.putString(MediaConst.OUTPUT_VIDEO_PATH, Environment.getExternalStorageDirectory().getAbsolutePath()+"/video");
//				bundle.putInt(MediaConst.MEDIA_RECORD_MAX_TIME, 30);
//				bundle.putBoolean(MediaConst.SHOW_CAMERA_PREVIEW, false);
//				bundle.putInt(MediaConst.OUTPUT_VIDEO_WIDTH_PX, 1280);
//				bundle.putInt(MediaConst.OUTPUT_VIDEO_HEIGHT_PX, 720);
//				bundle.putInt(MediaConst.VIDEO_ENCODING_BITRATE, 5*1024*512);
//				intent.putExtra(MediaConst.BUNDLE_DATA, bundle);
//				startActivityForResult(intent, 2);
			}
		});
		mbtnAudio.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(MainActivity.this, AudioWavesActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString(MediaConst.OUTPUT_AUDIO_PATH, Environment.getExternalStorageDirectory().getAbsolutePath()+"/arm");
				bundle.putInt(MediaConst.MEDIA_RECORD_MAX_TIME, 30);
				bundle.putSerializable(MediaConst.OUTPUT_AUDIO_FORMAT, OutputFormatMode.WAV);
				intent.putExtra(MediaConst.BUNDLE_DATA, bundle);
				startActivityForResult(intent, 3);
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode == RESULT_OK){
			switch (requestCode) {
			case 1:
				if (data != null && data.getData() != null) {
					Uri videoUri = data.getData();
					tvPath.setText(videoUri.getPath());
				}
				break;
			case 2:
				if (data != null && data.getData() != null) {
					Uri videoUri = data.getData();
					tvPath.setText(videoUri.getPath());
				}
				break;
			case 3:
				if (data != null && data.getData() != null) {
					Uri videoUri = data.getData();
					tvPath.setText(videoUri.getPath());
				}
				break;
				
			default:
				break;
			}
		}
	}

	 @SuppressWarnings("deprecation")
	private int getCameraId(boolean useFrontCamera) {
	        int count = Camera.getNumberOfCameras();
	        int result = -1;

	        if (count > 0) {
	            result = 0;

	            Camera.CameraInfo info = new Camera.CameraInfo();
	            for (int i = 0; i < count; i++) {
	                Camera.getCameraInfo(i, info);

	                if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK
	                        && !useFrontCamera) {
	                    result = i;
	                    break;
	                } else if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT
	                        && useFrontCamera) {
	                    result = i;
	                    break;
	                }
	            }
	        }
	        return result;
	    }
	 
	public Bitmap Bytes2Bimap(byte[] b) {
		if (b.length != 0) {
			return BitmapFactory.decodeByteArray(b, 0, b.length);
		} else {
			return null;
		}
	}

	public static Bitmap drawableToBitmap(Drawable drawable) {
		// 取 drawable 的长宽
		int w = drawable.getIntrinsicWidth();
		int h = drawable.getIntrinsicHeight();

		// 取 drawable 的颜色格式
		Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
				: Bitmap.Config.RGB_565;
		// 建立对应 bitmap
		Bitmap bitmap = Bitmap.createBitmap(w, h, config);
		// 建立对应 bitmap 的画布
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, w, h);
		// 把 drawable 内容画到画布中
		drawable.draw(canvas);
		return bitmap;
	}
}
